package com.matrix.rabbitmqtest.workqueues;

import com.matrix.rabbitmqtest.util.AppKeys;
import com.matrix.rabbitmqtest.util.RabbitMQUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.Map;
import java.util.stream.IntStream;

/**
 * 一个工作线程
 */
public class Worker {

    public static void main(String[] args) throws IOException {
        // 声明队列
        RabbitMQUtil.getChannel().queueDeclare(AppKeys.QUEUE_NAME, false, false, true, (Map) null);
        IntStream.range(0, 2).forEach(i -> {
            new Thread(() -> {
                try {
                    Channel channel = RabbitMQUtil.getChannel();
                    channel.basicQos(1);
                    String currentThreadName = Thread.currentThread().getName();
                    System.out.println(currentThreadName + "等待接收消息...");
                    channel.basicConsume(AppKeys.QUEUE_NAME, false, new DefaultConsumer(channel) {
                        @Override
                        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                            System.out.println(currentThreadName + "接收到消息:" + new String(body));
//                            ThreadUtil.sleep("T0".equals(currentThreadName) ? 5 : 30000);
                            System.out.println(currentThreadName + "完成消费:" + new String(body));
                            getChannel().basicAck(envelope.getDeliveryTag(), false);
                        }

                        @Override
                        public void handleCancel(String consumerTag) throws IOException {
                            System.out.println(currentThreadName + "触发取消消息:");
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }, "T" + i).start();
        });

    }
}
